"""
管理员管理 API
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel, Field
import uuid

from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.core.permissions import require_role
from app.core.security import hash_password
from app.models.user import User
from app.schemas.user import UserResponse

router = APIRouter(prefix="/admin", tags=["管理员管理"])


# ==================== Schemas ====================

class AdminCreateRequest(BaseModel):
    """创建管理员请求"""
    phone: str = Field(..., description="手机号")
    password: str = Field(..., min_length=6, max_length=72, description="密码")
    nickName: str = Field(..., alias="nick_name", description="昵称")
    role: str = Field(..., description="角色: venue_manager, city_manager, super_admin")
    
    class Config:
        populate_by_name = True


class AdminUpdateRequest(BaseModel):
    """更新管理员请求"""
    nickName: Optional[str] = Field(None, alias="nick_name", description="昵称")
    role: Optional[str] = Field(None, description="角色")
    password: Optional[str] = Field(None, min_length=6, max_length=72, description="新密码")
    
    class Config:
        populate_by_name = True


class AdminListResponse(BaseModel):
    """管理员列表响应"""
    total: int
    items: List[UserResponse]


# ==================== APIs ====================

@router.get("/list", response_model=AdminListResponse)
@require_role("super_admin")
async def list_admins(
    page: int = 1,
    page_size: int = 20,
    role: Optional[str] = None,
    keyword: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取管理员列表（仅超级管理员）
    
    - **page**: 页码
    - **page_size**: 每页数量
    - **role**: 角色筛选 (venue_manager, city_manager, super_admin)
    - **keyword**: 搜索关键词（手机号或昵称）
    """
    query = db.query(User).filter(
        User.role.in_(["venue_manager", "city_manager", "super_admin"])
    )
    
    # 角色筛选
    if role:
        query = query.filter(User.role == role)
    
    # 关键词搜索
    if keyword:
        query = query.filter(
            (User.phone.like(f"%{keyword}%")) | 
            (User.nick_name.like(f"%{keyword}%"))
        )
    
    # 总数
    total = query.count()
    
    # 分页
    items = query.order_by(User.created_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
    
    return {
        "total": total,
        "items": [UserResponse.from_orm(item) for item in items]
    }


@router.post("/create")
@require_role("super_admin")
async def create_admin(
    request: AdminCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    创建管理员（仅超级管理员）
    
    - **phone**: 手机号（登录账号）
    - **password**: 密码
    - **nick_name**: 昵称
    - **role**: 角色
      - venue_manager: 场地管理员
      - city_manager: 城市管理员
      - super_admin: 超级管理员
    """
    # 验证角色
    valid_roles = ["venue_manager", "city_manager", "super_admin"]
    if request.role not in valid_roles:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"无效的角色，必须是: {', '.join(valid_roles)}"
        )
    
    # 检查手机号是否已存在
    existing_user = db.query(User).filter(User.phone == request.phone).first()
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该手机号已被使用"
        )
    
    # 创建管理员
    admin = User(
        id=str(uuid.uuid4()),  # 生成 UUID
        phone=request.phone,
        password_hash=hash_password(request.password),
        nick_name=request.nickName,
        role=request.role,
        avatar="https://minio.aqilmini.com/football/default-avatar.png"
    )
    
    db.add(admin)
    db.commit()
    db.refresh(admin)
    
    return {
        "code": 200,
        "message": "管理员创建成功",
        "data": UserResponse.from_orm(admin)
    }


@router.put("/{admin_id}")
@require_role("super_admin")
async def update_admin(
    admin_id: str,
    request: AdminUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    更新管理员信息（仅超级管理员）
    
    - **admin_id**: 管理员ID
    - **nick_name**: 新昵称（可选）
    - **role**: 新角色（可选）
    - **password**: 新密码（可选）
    """
    # 查找管理员
    admin = db.query(User).filter(User.id == admin_id).first()
    if not admin:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="管理员不存在"
        )
    
    # 不能修改自己的角色
    if admin_id == current_user.id and request.role:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能修改自己的角色"
        )
    
    # 更新信息
    if request.nickName:
        admin.nick_name = request.nickName
    
    if request.role:
        valid_roles = ["user", "venue_manager", "city_manager", "super_admin"]
        if request.role not in valid_roles:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"无效的角色，必须是: {', '.join(valid_roles)}"
            )
        admin.role = request.role
    
    if request.password:
        admin.password_hash = hash_password(request.password)
    
    db.commit()
    db.refresh(admin)
    
    return {
        "code": 200,
        "message": "管理员信息更新成功",
        "data": UserResponse.from_orm(admin)
    }


@router.delete("/{admin_id}")
@require_role("super_admin")
async def delete_admin(
    admin_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    删除管理员（仅超级管理员）
    
    - **admin_id**: 管理员ID
    """
    # 不能删除自己
    if admin_id == current_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能删除自己"
        )
    
    # 查找管理员
    admin = db.query(User).filter(User.id == admin_id).first()
    if not admin:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="管理员不存在"
        )
    
    # 删除（软删除：将角色改为 user）
    admin.role = "user"
    db.commit()
    
    return {
        "code": 200,
        "message": "管理员已移除"
    }


@router.get("/{admin_id}", response_model=UserResponse)
@require_role("super_admin")
async def get_admin_detail(
    admin_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取管理员详情（仅超级管理员）
    
    - **admin_id**: 管理员ID
    """
    admin = db.query(User).filter(User.id == admin_id).first()
    if not admin:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="管理员不存在"
        )
    
    return UserResponse.from_orm(admin)

